package io.zhengsh.nio.buffer;

import org.junit.Test;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.IntBuffer;
import java.nio.channels.FileChannel;

public class BufferDemo1 {
    public static void main(String[] args) {

    }


    @Test
    public void buffer01() throws IOException {
        // FileChannel
        String pathName = "/Users/zhengsh/sourcecode.io/zhengsh-vvip/nio/src/main/resources/01.txt";
        RandomAccessFile accessFile =
                new RandomAccessFile(pathName, "rw");
        FileChannel channel = accessFile.getChannel();

        // 创建 buffer , 大小
        ByteBuffer buffer = ByteBuffer.allocate(1024);

        // 读
        int bytesRead = channel.read(buffer);
        while (bytesRead != -1) {
            // read 模式
            buffer.flip();

            while (buffer.hasRemaining()) {
                System.out.println((char) buffer.get());
            }
            buffer.clear();

            channel.read(buffer);
        }

        accessFile.close();
    }


    @Test
    public void buffer02() {

        // 创建 buffer
        IntBuffer buffer = IntBuffer.allocate(8);
        for (int i = 0; i < buffer.capacity(); i++) {
            int j = 2 * (i + 1);
            buffer.put(j);
        }

        // 重置缓冲区
        buffer.flip();

        while (buffer.hasRemaining()) {
            int value = buffer.get();
            System.out.println(value + "  ");
        }
    }
}
